#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2021/12/21 13:15
    Desc  :
--------------------------------------
"""
import urllib.request
from urllib import parse

from apiview_doc.decorator import api_doc
from django.http import HttpResponse
from django.urls import path
from django_http_log.common.request import BaseAPIView
from django_http_log.common.response import SuccessResponse, CommonResponse, ParamsErrorResponse, \
    SystemExceptionResponse
from tablib import Dataset

from common.decorator.token_decorator import Authentication
from common.enums.response_enums import get_status_code, CommonResultEnums
from common.exceptions import MicroseerException
from common.utils.log_utils import logger
from common.utils.token_utils import RequestAuthTokenUtil
from common.utils.tool_utils import read_case_import_file
from extends.microseer.base.upload import upload_file
from extends.microseer.roster.recruit import candidate_import_excel, push_person_info_import_excel, \
    person_barch_import_excel
from person.models import CaseModule
from platform_auth.settings import APIDOC_DECORATOR
from common.utils.random_utils import *
from django.db import transaction


class ApiDocAPIView(BaseAPIView):

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'doc', desc = '接口管理')
    @APIDOC_DECORATOR.ApiOperation(summary = '接口文档', path = '/base/docs', method = "GET")
    def get(self, request, *args, **kwargs):
        context = api_doc()

        context['status_code'] = get_status_code()

        return SuccessResponse(result = context)


class RandomUserInfoAPIView(BaseAPIView):

    def get(self, request, *args, **kwargs):

        body = request.query_params.copy()

        num = body.get('num')

        user_info_list = []

        if isinstance(num, int):
            return CommonResponse(codeEnums = CommonResultEnums.PARAMS_EXCEPTION)
        for i in range(int(num)):
            user_info_dict = {}
            user_info_dict['name'] = f'测试{random_name()}二要素'
            user_info_dict['phone'] = random_phone()
            user_info_dict['cardCode'] = random_ssn(max_age = 55, min_age = 18)
            user_info_list.append(user_info_dict)
        return SuccessResponse(result = user_info_list)


class RandomMethodAPIView(BaseAPIView):

    def get(self, request, *args, **kwargs):
        return SuccessResponse(result = global_methods)


class RandomUserInfoExportAPIView(BaseAPIView):

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'doc', desc = '接口管理')
    @APIDOC_DECORATOR.ApiOperation(summary = '候选人导入excel生成', path = '/base/candidateExport', method = "GET")
    @APIDOC_DECORATOR.ApiParams(value = 'demandId', require = True, type = 'int', desc = '订单id')
    @APIDOC_DECORATOR.ApiParams(value = 'num', require = True, type = 'int', desc = '生成数据的数量')
    @APIDOC_DECORATOR.ApiParams(value = 'env', require = True, type = 'String', desc = '环境', example = 'pre, prod')
    @APIDOC_DECORATOR.ApiParams(value = 'mscid', require = True, type = 'int', desc = 'mscid')
    @APIDOC_DECORATOR.ApiParams(value = 'type', require = True, type = 'int', desc = '导出类型',
                                remark = '#101 候选人导入 #102 推送人员导入')
    @APIDOC_DECORATOR.ApiParams(value = 'fileName', type = 'Steing', desc = '文件名称')
    def get(self, request, *args, **kwargs):
        type_enum = ['101', '102', '103']
        env_enum = ['pre', 'prod']
        # try:
        body = request.query_params.copy()
        num = int(body.get('num'))
        demandId = body.get('demandId')
        env = body.get('env')
        mscid = body.get('mscid')
        type = body.get('type')

        if body.get('fileName'):
            file_name = parse.quote(body.get('fileName'))
        else:
            file_name = parse.quote("导出文件")
        res = HttpResponse(content_type = 'application/ms-excel')
        res['Content-Disposition'] = f'attachment; filename="{file_name}.xls"'
        try:
            if type not in type_enum:
                return ParamsErrorResponse(code = 40002, message = 'type参数不合法')
            if env not in env_enum:
                return ParamsErrorResponse(code = 40002, message = 'env参数不合法')
            if type == '101':
                output = candidate_import_excel(demandId = demandId, num = num, env = env, mscid = mscid)
            elif type == '102':
                output = push_person_info_import_excel(demandId = demandId, num = num, env = env, mscid = mscid)
            elif type == '103':
                output = person_barch_import_excel(num = num)
        except MicroseerException as e:
            logger.error(e)
            return ParamsErrorResponse(code = 41000, message = str(e))
        res.write(output.getvalue())
        return res
        # except Exception as e:
        #     logger.error(e)
        #     return SystemExceptionResponse()


class ApiTestAPIView(BaseAPIView):

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'test', desc = '测试管理')
    @APIDOC_DECORATOR.ApiOperation(summary = '测试数据', path = '/base/test', method = "POST")
    @APIDOC_DECORATOR.ApiParams(value = 'filePath', require = True, type = 'string', desc = '文件地址')
    @Authentication(isProject = True)
    def post(self, request, *args, **kwargs):

        try:
            projectId = RequestAuthTokenUtil(request = request).get_project()
            filePath = request.data.copy().get('filePath')
            data = read_case_import_file(project = projectId, filePath = filePath)
            return SuccessResponse(result = data)

        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()


class UploadFileAPIView(BaseAPIView):

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'base', desc = '基础服务')
    @APIDOC_DECORATOR.ApiOperation(summary = '文件上传', path = '/base/upload', method = "POST")
    @APIDOC_DECORATOR.ApiParams(value = 'file', require = True, type = 'file', desc = '文件')
    def post(self, request, *args, **kwargs):
        try:
            files = request.FILES.get('file')
            flag, data = upload_file(file = files)
            if flag:
                return SuccessResponse(result = data)
            else:
                return ParamsErrorResponse(code = 41001, message = data)
        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()


urlpatterns = [
    path('doc', ApiDocAPIView.as_view()),
    path('random', RandomUserInfoAPIView.as_view()),
    path('methods', RandomMethodAPIView.as_view()),
    path('candidateExport', RandomUserInfoExportAPIView.as_view()),
    path('test', ApiTestAPIView.as_view()),
    path('upload', UploadFileAPIView.as_view()),
]
